/*
 * @LastEditors: 田迅
 */
var moneyReg=/(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/; //金额正则带两位小数的正数
var formReg=/\s*/; //简单匹配输入内容不能有回车空格换行
var passReg=/^\d*$/; //匹配纯数字
var priceReg = /[^\d\.]/g; //价格正则
var numReg=/[^0-9]/g;//数字正则

// 验证字符串为空
function isStrNull(str) {
  var text = str.replace(/(^\s*)|(\s*$)/g, '');
  if(text){
    return true;
  }else{
    return false;
  }
}

$(function() {
    try {
        FastClick.attach(document.body);
        $("body").on("click",'input',function(e) {
            e.target.focus();
        });
    } catch (e) {
        //   console.log(e);
    }
});

//js移动端原生拨打号码 location.href="tel:"+a
function call($num){
  location.href="tel:"+$num;
}

//js原生判断当前手机语言环境
function isEn() {
  var language = (navigator.language || navigator.browserLanguage).toLowerCase();
  var flag = false;
  if(language.indexOf('en')>-1){
     flag = true;
  }else {
     flag = false;
  }
  return flag;
}



// 将时间总毫秒数转换为'00:00'格式
function getTimes($time){
	var second=parseInt($time/1000)%60;
	var minute=parseInt(parseInt($time/1000)/60);
	if(second<10){
		second="0"+second;
	}
	if(minute<10){
		minute="0"+minute;
	}
	var time=minute+":"+second;
  return time;
}

//传入秒数转换为2018-01-01 01:01格式日期
function getMyDate($second){
    var oDate = new Date($second);
    var oYear = oDate.getFullYear();
    var oMonth = oDate.getMonth()+1;
    var oDay = oDate.getDate();
    var oHour = oDate.getHours();
    var oMin = oDate.getMinutes();
    if(oMonth<10){
      oMonth="0"+oMonth;
    }
    if(oDay<10){
      oDay="0"+oDay;
    }
    if(oHour<10){
      oHour="0"+oHour;
    }
    if(oMin<10){
      oMin="0"+oMin;
    }
    var oTime=oYear+"-"+oMonth+"-"+oDay+" "+oHour+":"+oMin;
    // oSen = oDate.getSeconds(),
    // oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) +' '+ getzf(oHour) +':'+ getzf(oMin) +':'+getzf(oSen);//最后拼接时间
    return oTime;
};

//获取当前指定2018-01-01格式日期
function getNowDate(){
    var nDate = new Date();
    var nYear = nDate.getFullYear();
    var nMonth = nDate.getMonth()+1;
    var nDay = nDate.getDate();
    if(nMonth<10){
      nMonth="0"+nMonth;
    }
    if(nDay<10){
      nDay="0"+nDay;
    }
    var nTime=nYear+"-"+nMonth+"-"+nDay;
    // oSen = oDate.getSeconds(),
    // oTime = oYear +'-'+ getzf(oMonth) +'-'+ getzf(oDay) +' '+ getzf(oHour) +':'+ getzf(oMin) +':'+getzf(oSen);//最后拼接时间
    return nTime;
};

//canvas截图  依赖html2canvas.js
  function screenShot($element,callBack){
    var w = $element.width();
    var h = $element.height();

    //要将 canvas 的宽高设置成容器宽高的 2 倍
    var canvas = document.createElement("canvas");
    canvas.width = w * 2;
    canvas.height = h * 2;
    canvas.style.width = w + "px";
    canvas.style.height = h + "px";
    var context = canvas.getContext("2d");
    //然后将画布缩放，将图像放大两倍画到画布上
    context.scale(2,2);
    var rect = $element.get(0).getBoundingClientRect();//获取元素相对于视察的偏移量
    context.translate(-rect.left,-rect.top);//设置context位置，值为相对于视窗的偏移量负值，让图片复位
    html2canvas($element,{
        allowTaint: true, //允许污染
        taintTest: true, //在渲染前测试图片(没整明白有啥用)
        useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用,下面解释)
        canvas:canvas,
        onrendered: function(canvas) {//得到了canvas对象
          var imgUrl = canvas.toDataURL("image/png");//这里通过canvas的toDataURL方法把它转换成base64编码。
          return callBack(imgUrl);
        }
    });
  }

  //原生JS图片无法加载时onerror处理
  function nofind(_this){
  _this.src="../../image/login/logo.png";
  _this.onerror=null;
  }


//自定义日历
  function TXcalendar($num,get){
//方法一：var calendar= new TXcalendar($num,get); $num代表你要返回的日历有几页，默认从当前月份开始,get是回调方法；
//get回调返回一个数组，对象里的year代表年份,month代表月份,limit代表当前月份第一天对应的是星期几，
//比如返回的month是2,limit是2那就代表2月1日是星期二,daylist代表当前moth对应的天数数组，因为日历一般是宫格布局，所以返回天数数组的
//空字符则代表上个月月底的几天
//方法二：calendar.dateInit($year,$month,callback); 返回指定年月的日期列表
    if(arguments.length==1 || arguments.length>2){
      console.error("The number of incoming values is incorrect");
      return;
    }
    var year=new Date().getFullYear();
    var month=new Date().getMonth()+1;
    var temp=0;
    if(!$num){
      var num=1;
    }else{
      var num=$num;
    }
    var ArrayList=[];
    var that=this;
    //获取指定年份和月份的单张日历
    this.dateInit=function($year,$month,callback){
      var year=$year;
      if($month<10){
        var month="0"+$month;
      }else{
        var month=$month;
      }
      var emptyArray=[];
      var totailDay="";
      var dateTime=$year+"/"+$month+"/01";
      var week=new Date(dateTime).getDay(); //返回月初对应周数
      totailDay = new Date(year,month,0).getDate();
      totailDay=totailDay+week;
      for(var i=0;i<totailDay;i++){
        if(i<week){
          emptyArray.push("");
        }else{
          var num=i-week+1;
          emptyArray.push(num);
        }
      }
      function newObj($year,$month,$limit,$daylist){
          this.year=$year;
          this.month=$month;
          this.limit=$limit;
          this.daylist=$daylist;
      }
      var obj=new newObj(year,month,week,emptyArray);
      callback(obj);
    }
    this.getArrayList=function($year,$month){
      var year=$year;
      var month=$month;
      that.dateInit(year,month,function(obj){
        // console.log(JSON.stringify(obj));
        ArrayList.push(obj);
        temp+=1;
        if(temp==num){
          this.ArrayList=ArrayList;
          if(get){
            return get(this.ArrayList);
          }else{
            return this.ArrayList;
          }
        }
        if(month==12){
          month=1;
          year+=1;
          that.getArrayList(year,month);
        }else{
          month+=1;
          that.getArrayList(year,month);
        }
      });
    }
    this.getArrayList(year,month);
  }

  //防止多次点击
  function NewManyClickStop($temp,$interval,callBack){
    var reg1 = /^[0-9]\d*$/; //匹配正整数
    //console.error()
    if(!$temp&&$temp!=0){
      console.error('the parameter of first is not defind ');
      return;
    }
    if(!$interval&&$interval!=0){
      console.error('the parameter of second is not defind ');
      return;
    }
    if(!callBack){
      console.error('the parameter of third is not defind ');
      return;
    }
    //要求第一个值与第二个值必须是数字类型
    if(typeof($interval) != 'number' || typeof($temp) != 'number'){
      console.error('Wrong value type entered ');
      return;
    }
    if(typeof($interval) == 'number' || typeof($temp) == 'number'){
      //匹配第一个参数与第二个参数是否未正整数
      if(!reg1.test($interval) || !reg1.test($temp)){
        console.error('Wrong value type entered ');
        return;
      }
    }
    //获取当前毫秒值
    this.init=function(){
      var times=new Date().getTime();
      return times;
    }
    this.nowTime=this.init();
    if(arguments.length==3){
        if(this.nowTime>($temp+$interval)){
            var obj=new NewObj(this.nowTime,true);
        }else{
            var obj=new NewObj(this.nowTime,false);
        }
        callBack(obj);
    }else{
      return "incorrect number of parameters";
    }
    function NewObj($time,$bool){
      this.time=$time;
      this.bool=$bool;
    }
  }

//年月日picker选择器  依赖于iosselect.js iosselect.css  依赖jquery.js的attr方法
  function timeIosSelect($clickDom,$title,CallBack){
    var selectDateDom = $clickDom;
    // 初始化时间
    var now = new Date();
    var nowYear = now.getFullYear();
    var nowMonth = now.getMonth() + 1;
    var nowDate = now.getDate();
    // 数据初始化
    function formatYear (nowYear) {
        var arr = [];
        for (var i = nowYear; i <= nowYear + 5; i++) {
            arr.push({
                id: i + '',
                value: i + '年'
            });
        }
        return arr;
    }
    function formatMonth (num) {
        var arr = [];
        for (var i = num; i <= 12; i++) {
            arr.push({
                id: i + '',
                value: i + '月'
            });
        }
        return arr;
    }
    function formatDate (count,num) {
        var arr = [];
        for (var i = num; i <= count; i++) {
            arr.push({
                id: i + '',
                value: i + '日'
            });
        }
        return arr;
    }
    var yearData = function(callback) {
        // settimeout只是模拟异步请求，真实情况可以去掉
        // setTimeout(function() {
            callback(formatYear(nowYear))
        // }, 2000)
    }
    var monthData = function (year, callback) {
      var now = new Date();
      var nowYear = now.getFullYear();
      var nowMonth = now.getMonth() + 1;
        // settimeout只是模拟异步请求，真实情况可以去掉
        // setTimeout(function() {
        if(nowYear==year){
          callback(formatMonth(nowMonth));
        }else{
          callback(formatMonth(1));
        }

        // }, 2000);
    };
    var dateData = function (year, month, callback) {
        // settimeout只是模拟异步请求，真实情况可以去掉
            var now = new Date();
            var nowYear = now.getFullYear();
            var nowMonth = now.getMonth() + 1;
            var nowDate = now.getDate();
            if (/^(1|3|5|7|8|10|12)$/.test(month)) {
                if(nowMonth==month){
                  callback(formatDate(31,nowDate));
                }else{
                  callback(formatDate(31,1));
                }
            }
            else if (/^(4|6|9|11)$/.test(month)) {
              if(nowMonth==month){
                callback(formatDate(30,nowDate));
              }else{
                callback(formatDate(30,1));
              }
            }
            else if (/^2$/.test(month)) {
                if (year % 4 === 0 && year % 100 !==0 || year % 400 === 0) {
                  if(nowMonth==month){
                    callback(formatDate(29,nowDate));
                  }else{
                    callback(formatDate(29,1));
                  }
                }
                else {
                  if(nowMonth==month){
                    callback(formatDate(28,nowDate));
                  }else{
                    callback(formatDate(28,1));
                  }
                }
            }
            else {
                throw new Error('month is illegal');
            }
    };
    var hourList=function getHour(one,two,three,callback){
      var arr=[];
      for(var i=0;i<24;i++){
        if(i<10){
          var str="0"+i+'时';
        }else{
          var str=i+'时';
        }
        var obj=HMobj(i,str);
        arr.push(obj);
      }
      callback(arr);
    }
    var monthList=function getMonth(one,two,three,four,callback){
      var arr=[];
      var num=10;
      for(i=0;i<6;i++){
        if(i==0){
          var str="0"+num*i+'分';
        }else{
          var str=num*i+'分';
        }
        var id=i+1;
        var obj=HMobj(i,str);
        arr.push(obj);
      }
      callback(arr);
    }
    function HMobj($id,$value){
      var obj={
        id:$id,
        value:$value,
      }
      return obj;
    }
    selectDateDom.bind('click', function () {
        var iosSelect = new IosSelect(5,
            [yearData, monthData, dateData,hourList,monthList],
            {
                title: $title,
                itemHeight: 35,
                showLoading: true,
                showAnimate:true,
                callback: function (selectOneObj, selectTwoObj, selectThreeObj,hourObj,monthObj) {
                  CallBack(selectOneObj,selectTwoObj,selectThreeObj,hourObj,monthObj);
                }
        });
    });
  }

//单项picker选择器  依赖于iosselect.js iosselect.css
  function singleIosSelect(clickDom,ArrayList,title,CallBack){
    var showBankDom = document.querySelector(clickDom);
      showBankDom.addEventListener('click', function () {
          var bankSelect = new IosSelect(1,
              [ArrayList],
              {
                  title: title,
                  itemHeight: 50,
                  itemShowCount:5,
                  showAnimate:true,
                  callback: function (selectOneObj) {
                    CallBack(selectOneObj);
                  }
              });
      });
  }

  //双picker选择器  依赖于iosselect.js iosselect.css
    function doubleIosSelect(clickDom,ArrayList1,ArrayList2,id1,id2,title,CallBack){
      var showBankDom = document.querySelector(clickDom);
        showBankDom.addEventListener('click', function () {
          var oneId = showBankDom.dataset[id1];
          var twoId = showBankDom.dataset[id2];
            var bankSelect = new IosSelect(2,
                [ArrayList1,ArrayList2],
                {
                    title: title,
                    itemHeight: 50,
                    itemShowCount: 3,
                    oneLevelId: oneId,
                    twoLevelId: twoId,
                    showAnimate:true,
                    callback: function (selectOneObj,selectTwoObj) {
                      CallBack(selectOneObj,selectTwoObj);
                    }
                });
        });
    }

//省市区picker选择器  依赖于iosselect.js, iosselect.css,area.js
  function areaIosSelect($clickDom,title,CallBack){
    var selectContactDom = $($clickDom);
      selectContactDom.bind('click', function () {
          var iosSelect = new IosSelect(3,
              [iosProvinces, iosCitys, iosCountys],
              {
                  title: title,
                  itemHeight: 35,
                  relation: [1, 1],
                  callback: function (selectOneObj, selectTwoObj, selectThreeObj) {
                    CallBack(selectOneObj, selectTwoObj, selectThreeObj);
                  }
          });
      });
  }

function getWeek($seconds){
    var weeks=[' 星期日',' 星期一',' 星期二',' 星期三',' 星期四',' 星期五',' 星期六'];
    var num=new Date($seconds).getDay();
    return weeks[num];
}

//预约时间选择器
function newTimeIosSelect($clickDom,$title,CallBack){
  var selectContactDom = $($clickDom);
  var dayList=function(callback){
    var arr=[];
    var bool=true;
    for(var i=1;i<8;i++){
      var date=new Date();
      var hour=date.getHours();
      if(hour==23&&bool){
        bool=false;
        continue;
      }
      var seconds=date.getTime()+24*60*60*1000*(i-1);
      var newDate= new Date(seconds);
      var month =newDate.getMonth()+1;
      var day = newDate.getDate();
      if(i==1){var text=" 今天"};
      if(i==2){var text=" 明天"};
      if(i==3){var text=" 后天"};
      if(i>3){var text=getWeek(seconds);}
      var value=month+"月"+day+"日"+text;
      var obj=MDobj(day,value,month,day,text);
      arr.push(obj);
    }
    // console.log(JSON.stringify(arr));
    callback(arr);
  }
  var hourList=function(one,callback){
    var arr=[];
    var nDay=new Date().getDate();
    var nHour=new Date().getHours();
    var nMinute=new Date().getMinutes();
    for(var i=0;i<24;i++){
        if(nDay==one){
          if(i<nHour){
            continue;
          }else if(i==nHour&&nMinute>55){
            continue;
          }
        }
        var str=i+"点";
        var obj=HMobj(i,str);
        arr.push(obj);
    }
    callback(arr);
  }
  var monthList=function(one,two,callback){
    var arr=[];
    var num=5;
    var nDay=new Date().getDate();
    var nHour=new Date().getHours();
    var nMinute=new Date().getMinutes();
    for(i=0;i<12;i++){
      if(nDay==one&&nHour==two){
        if((i*5)<nMinute){
          continue;
        }
      }
      var str=num*i+"分";
      var obj=HMobj(i*num,str);
      arr.push(obj);
    }
    callback(arr);
  }
  selectContactDom.bind('click', function () {
      var iosSelect = new IosSelect(3,
          [dayList,hourList,monthList],
          {
            title: $title,
            itemHeight: 35,
            itemShowCount: 5,
            showAnimate:true,
            callback: function (oneObj,twoObj,threeObj) {
              CallBack(oneObj,twoObj,threeObj);
            }
      });
  });
  function MDobj($id,$value,$month,$day,$text){
    var obj={
      id:$id,
      value:$value,
      month:$month,
      day:$day,
      text:$text,
    }
    return obj;
  }
  function HMobj($id,$value){
    var obj={
      id:$id,
      value:$value,
    }
    return obj;
  }
}

//自定义选择器
function myTimeIosSelect($clickDom,$title,CallBack){
  var selectContactDom = $($clickDom);
  var hourList=function getHour(callback){
    var arr=[];
    for(var i=0;i<24;i++){
      if(i<10){
        var str="0"+i+'时';
      }else{
        var str=i+'时';
      }
      var obj=HMobj(i,str);
      arr.push(obj);
    }
    callback(arr);
  }
  var monthList=function getMonth(one,callback){
    var arr=[];
    var num=10;
    for(i=0;i<6;i++){
      if(i==0){
        var str="0"+num*i+'分';
      }else{
        var str=num*i+'分';
      }
      var id=i+1;
      var obj=HMobj(i,str);
      arr.push(obj);
    }
    callback(arr);
  }
  selectContactDom.bind('click', function () {
      var iosSelect = new IosSelect(2,
          [hourList,monthList],
          {
            title: $title,
            itemHeight: 35,
            itemShowCount: 5,
            showAnimate:true,
            callback: function (oneObj,twoObj) {
              CallBack(oneObj,twoObj);
            }
      });
  });
  function MDobj($id,$value,$month,$day,$text){
    var obj={
      id:$id,
      value:$value,
      month:$month,
      day:$day,
      text:$text,
    }
    return obj;
  }
  function HMobj($id,$value){
    var obj={
      id:$id,
      value:$value,
    }
    return obj;
  }
}


//二级联动选择器 依赖于iosselect.js iosselect.css
function secondIosSelect($clickDom,$ArrayList,$title,CallBack,FallBack){
  var showBankDom = $clickDom;
  var secondList=function getSecond(second,callback){
      Apiajax("goods/IdsGetAddress",{addres_id:second},function(s,err){
        // console.log(JSON.stringify(s));
        // console.log(JSON.stringify(err));
        if(s){
          if(s.status==1){
            if(s.data.length!=0){
              callback(s.data);
            }else{
              callback([{id:1,value:'无服务'}]);
            }
          }else{
            callback([{id:1,value:'无服务'}]);
          }
        }
      })
  }
  showBankDom.bind('click', function () {
    var bankSelect = new IosSelect(2,
        [$ArrayList,secondList],
        {
            title: $title,
            itemHeight: 50,
            itemShowCount:5,
            showAnimate:true,
            callback: function (selectOneObj,selectTwoObj) {
              CallBack(selectOneObj,selectTwoObj);
            },
            fallback:function(){
              if(FallBack){
                FallBack('fall');
              }
            },
            maskCallback:function(){
              if(FallBack){
                FallBack('mask');
              }
            }
        });
  });
}

// 轮播
var mySwiper;
function beginSlide(){
	if(mySwiper){
		mySwiper.destroy(true);
	}
	mySwiper = new Swiper('.swiper-container', {
    observer:true,
    observeParents:true,
    loop: false,
    autoplay: {
      delay: 3000,
      stopOnLastSlide: false,
      disableOnInteraction: false,
    },
		pagination: {
			el: '.swiper-pagination',
			type : 'bullets',
			bulletElement : 'li',
		},
		on: {
			slideChangeTransitionStart: function(){
				// alert(this.activeIndex);
				for(var i=0;i<$(".swiper-pagination li").length;i++){
					$(".swiper-pagination li").css({"width":"8px","background-color":"#fff","opacity":1});
				}
				$(".swiper-pagination li:eq("+this.activeIndex+")").css({"width":"20px","background-color":"#5893ff"});
			},
		},
	})
  $(".swiper-pagination li").css({"background-color":"#fff","opacity":1});
	$(".swiper-pagination li:eq(0)").css({"width":"20px","background-color":"#5893ff"});
}

//省市区picker选择器  依赖于iosselect.js, iosselect.css,area.js
function areaIosSelect($clickDom,title,CallBack){
  var selectContactDom = $($clickDom);
  var iosProvinces=function(callback){
    Apiajax("goods/GetAddress",{}, function (s, err) {
        if(s){
          callback(s.data);
        }
      })
  }
  var iosCitys=function(one,callback){
    // console.log(one);
    Apiajax("goods/IdsGetAddress",{addres_id:one}, function (s, err) {
      // console.log(JSON.stringify(s));
      // console.log(JSON.stringify(err));
        if(s){
          callback(s.data);
        }
      })
  }
  var iosAreas=function(one,two,callback){
    Apiajax("goods/IdsGetAddress",{addres_id:two}, function (s, err) {
        if(s){
          callback(s.data);
        }
    })
  }
    selectContactDom.bind('click', function () {
        var iosSelect = new IosSelect(3,
            [iosProvinces,iosCitys,iosAreas],
            {
                title: title,
                itemHeight: 35,
                relation: [1, 1],
                callback: function (selectOneObj,selectTwoObj,selectThreeObj) {
                  CallBack(selectOneObj,selectTwoObj,selectThreeObj);
                }
        });
    });
}

// 监听页面图片是否加载完成
// document.getElementById('img').onload=function(){
//   console.log(1);
// }

//数字转价格
function price_transform($num){
  var s=String($num)
  var rs = s.indexOf('.');
  if (rs < 0) {
      rs = s.length;
      s += '.';
  }
  while (s.length <= rs + 2) {
      s += '0';
  }
  return s;
}
